<!-- 房屋管理 -->
<template>
  <div class="root-house-mng">
    <div class="root-house-mng-main">
      <ImagePreview :imageList="imgList" />

      <Tabs v-model:activeKey="activeKeyRef" type="line" size="small">
        <template #rightExtra>
          <Space :size="8" v-if="'list' == activeKeyRef">
            <a-button type="primary" @click="handleReloadCurrent"> 刷新当前页 </a-button>
          </Space>
        </template>
        <!-- <TabPane key="map" tab="地图模式">
          <HouseMap
            mapViewId="houseMap"
            :showMapPopupButtons="showMapPopupButtons"
            @on-popup-button-ok-click="onPopupButtonOkClick"
            ref="houseMapRef"
          />
        </TabPane> -->
        <TabPane key="list" tab="解绑管理">
          <BasicTable @register="registerTable">
            <template #id="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'ant-design:picture',
                    tooltip: '预览',
                    onClick: handlePreview.bind(null, record),
                  },
                ]"
              />
            </template>
            <template #action="{ record }">
              <TableAction :actions="getTableActs(record)" />
            </template>
          </BasicTable>
        </TabPane>
      </Tabs>
    </div>

    <AuditModal @register="registerModal" @success="handleSuccess" />

    <Drawer5 @register="register5">
      <template #drawContent>
        <DataTableList
          v-if="policeVisible"
          :houseId="pickedHouseId"
          ref="housePolicePlaceRef"
          @house-submit="handleSuccess"
        />
        <FireTableList
          v-if="fireVisible"
          :houseId="pickedHouseId"
          ref="houseFirePlaceRef"
          @house-submit="handleSuccess"
        />
        <Tag v-if="!policeVisible && !fireVisible"></Tag>
      </template>
    </Drawer5>
  </div>
</template>

<script lang="ts">
  //import maplibregl from '/@/utils/lib/mapre/maplibre-gl.js';
  //import '/@/utils/lib/mapre/maplibre-gl.css';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getBasicColumns, tablePopupSchema } from './tableData';
  import { PageWrapper } from '/@/components/Page';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Tabs, Space, Divider, Drawer, Tag, Collapse, Button, Popover } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import {
    defineComponent,
    onMounted,
    reactive,
    ref,
    ComputedRef,
    computed,
    defineAsyncComponent,
    nextTick,
  } from 'vue';
  import {
    downloadByUrl,
    downloadByData,
    downloadByBase64,
    downloadByOnlineUrl,
  } from '/@/utils/file/download';
  import { houseListApi, houseApi } from '/@/api/demo/table';
  import * as tableDataPopup from '/@/views/map/tableDataPopup';
  import { useGlobSetting } from '/@/hooks/setting';
  const globSetting = useGlobSetting();
  import { getSearchFormSchema } from '/@/views/house/tableDatajb';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  const { info, success, warning, error } = createMessage;
  import { FormProps, FormSchema } from '/@/components/Table';
  import AuditModal from './AuditModal.vue';
  import HouseMap from './HouseMap.vue';
  import { useModal } from '/@/components/Modal';
  import type { UserInfo } from '/#/store';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import Drawer5 from '/@/views/detail/Drawer5.vue';
  import { useDrawer } from '/@/components/Drawer';
  const DataTableList = defineAsyncComponent(
    () => import('/@/views/danger/comprehensive/DataTableListMergeAll.vue'),
  );

  const FireTableList = defineAsyncComponent(
    () => import('/@/views/danger/fire/FireTableListMergeAll.vue'),
  );

  import querystring from 'query-string';
  import { fwbhjb } from '/@/api/demo/system';
  const imgList: string[] = [];
  export default defineComponent({
    name: 'HouMng',
    components: {
      DataTableList,
      FireTableList,
      ImagePreview,
      BasicTable,
      BasicForm,
      AuditModal,
      TableAction,
      PageWrapper,  
      Tabs,
      Divider,
      Drawer5,
      Space,
      SearchOutlined,
      Popover,
      HouseMap,
      Tag,
      TabPane: Tabs.TabPane,
      Button,
    },
    props: {
      msg: String,
      showMapPopupButtons: {
        type: Boolean,
        default: true,
      },
      policeVisible: {
        type: Boolean,
        default: false,
      },
      fireVisible: {
        type: Boolean,
        default: false,
      },
    },
    setup(props, { attrs, emit, slots, expose }) {
      const activeKeyRef = ref('list');
      const activePickKeyRef = ref('fire');
      const searchVisible = ref(false);
      const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
       
      const pickedHouse = ref({});
      const pickedHouseId = ref('');
      const houseFirePlaceRef = ref();
      const housePolicePlaceRef = ref();

      const houseMapRef = ref();

      const userStore = useUserStore();

      function calcModes(user: UserInfo) {
        if (user) {
          if ('Admin' == user.role) {
            return ['fire', 'police', 'housing'];
          } else {
            if ('FireControl' == user.userGroup) {
              return ['fire'];
            } else if ('Police' == user.userGroup) {
              return ['police'];
            } else if ('Housing' == user.userGroup) {
              return ['housing'];
            }
          }
        }

        return [];
      }

      function getTableActs(record) {
        let acts = [
          {
            icon: 'clarity:map-marker-line',
            tooltip: '定位2',
            onClick: handleLocMap.bind(null, record),
          },
        ];

        if (props.showMapPopupButtons) {
          acts.push({
            icon: 'clarity:tree-view-line',
            tooltip: '核查历史情况',
            onClick: handlePlaceView.bind(null, record),
          });
        }
        if (props.showMapPopupButtons) {
          acts.push({
            icon: 'ant-design:edit-filled',
            tooltip: '自查解绑',
            // 提示框组件
            popConfirm: {
              title: '是否确认解绑',
              confirm: fwbhjb1.bind(null, record),
            },
           
          });
        }
        return acts;
      }

      const underMode = calcModes(userStore.getUserInfo);

      const tk = userStore.getToken;
      let protocol = window.document.location.protocol;
      let host = window.document.location.host;
      let localhostPath = protocol + '//' + host;

      const mapopC: maplibregl.Popup[] = [];
      function clickPopUpOk(_) {
        if (mapopC.length > 0) {
          mapopC[0].remove();
        }
      }

      const [register5, { openDrawer: openDrawer5, setDrawerProps }] = useDrawer();

      //获取当前房屋的历史纪录(自查\检查\核查)
      function clickPopupButtonOk(obj) {
        console.log(obj);
        pickedHouse.value = obj;
        pickedHouseId.value = obj.fwbh;
        setDrawerProps({
          destroyOnClose: true,
          showDetailBack: false,
          afterVisibleChange: (visible: boolean) => {
            if (visible) {
              nextTick(() => {
                // houseFirePlaceRef.value.onHouseSelected(obj.id);
                // housePolicePlaceRef.value.onHouseSelected(obj.id);
              });
            }
          },
        });
        openDrawer5(true);
      }
 //(自查解绑\检查\核查)
 function clickPopupButtonOkjb(obj) {
        
        // pickedHouse.value = obj;
        // pickedHouseId.value = obj.fwbh;
        console.log(obj.fwbh);

        // 如果需要，传递其他参数
  

        // setDrawerProps({
        //   destroyOnClose: true,
        //   showDetailBack: false,
        //   afterVisibleChange: (visible: boolean) => {
        //     if (visible) {
        //       nextTick(() => {
        //         // houseFirePlaceRef.value.onHouseSelected(obj.id);
        //         // housePolicePlaceRef.value.onHouseSelected(obj.id);
        //       });
        //     }
        //   },
        // });
        // openDrawer5(true);
      }
      const [registerModal, callbackUseModal] = useModal();

      function cloneSearchSchema(serSchema: FormSchema[]) {
        var serSchemaClone: FormSchema[] = [];
        serSchema.forEach((ele) => {
          const a: FormSchema = Object.assign({}, ele);
          a.colProps = { span: 12, flex: 1 };
          serSchemaClone.push(a);
        });
        return serSchemaClone;
      }

      var serSchema = getSearchFormSchema(underMode); //获取查询条件
      const [registerTable, { reload, getForm }] = useTable({
        api: houseListApi,
        columns: getBasicColumns(),
        pagination: { pageSize: 15 },
        formConfig: {
          schemas: cloneSearchSchema(serSchema),
        },
        useSearchForm: true,
        bordered: true,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function handleReloadCurrent() {
        reload(); //刷新当前页
      }
      function toMapData(data, prefix, ret) {
        for (let d in data) {
          if (typeof data[d] == 'object') {
            toMapData(data[d], d, ret);
          } else {
            if (prefix) {
              ret[`${prefix}.${d}`] = data[d];
            } else {
              ret[d] = data[d];
            }
          }
        }
      }

      function encodeData(data) {
        let dv = {};
        toMapData(data, '', dv);
        return Object.keys(dv)
          .map(function (key) {
            return [key, dv[key]].map(encodeURIComponent).join('=');
          })
          .join('&');
      }

      function handleExport() {
        const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
        const tk = userStore.getToken;

        const fv = getForm().getFieldsValue();
        const searchParams = encodeData(fv);
        console.log(searchParams);
        downloadByUrl({
          url: `${uriBase}/houses/datas/export?access_token=${tk}&${searchParams}`,
          target: '_blank',
        });
      }

      function handleReload() {
        reload({
          page: 1,
        });
      }

      function handleSuccess() {
        reload();
      }

      function handlePreview(record: Recordable) {
        const onImgLoad = ({ index, url, dom }) => {
          console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
        };
        imgList.length = 0;
        if (record.photos) {
          let photos = record.photos.split(',');
          photos.forEach((ele) => {
            if (ele) imgList.push(`${globSetting.apiBaseUrl}/api/v1/images22222/${ele}`);
          });
        }
        // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
        createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
      }

      function handleStatus(a: Recordable) {
        // if(record.pcztFire===21||record.pcztFire===20||record.pcztFire===1){
        //   record.pcztFire=2
        // }
        var record = JSON.parse(JSON.stringify(a));
        callbackUseModal.openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function onPopupButtonOkClick(obj) {
        clickPopupButtonOk(obj);
      }

      function handlePlaceView(record: Recordable) {
        clickPopupButtonOk(record);
      }
       function fwbhjb1(record: Recordable) {
         console.log("fwbhjb",record.id);
         fwbhjb(record);

         reload();
      }

 

      function handleLocMap(record: Recordable) {
        activeKeyRef.value = 'map';
        houseMapRef.value.handleLocMap(record);
      }

      function locMap(houseId) {
        houseMapRef.value.locMap(houseId);
      }

      const getFormProps = computed((): Partial<FormProps> => {
        return {
          showAdvancedButton: false,
          compact: true,
          actionColOptions: { span: 6 },
          schemas: cloneSearchSchema(serSchema),
        };
      });

      function handleSearchInfoChange(info: Recordable) {}
      const [registerForm, formActions] = useForm();
      const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
        const keys = Object.keys(slots);
        return keys
          .map((item) => (item.startsWith('form-') ? item : null))
          .filter((item) => !!item) as string[];
      });
      function replaceFormSlotKey(key: string) {
        if (!key) return '';
        return key?.replace?.(/form\-/, '') ?? '';
      }
      const showDrawer = () => {
        searchVisible.value = true;
      };
      return {
        imgList,
        activeKeyRef,
        activePickKeyRef,
        registerForm,
        getFormSlotKeys,
        replaceFormSlotKey,
        getFormProps,
        handleSearchInfoChange,
        registerTable,
        handlePreview,
        handleLocMap,
        handleStatus,
        handleReloadCurrent,
        handleExport,
        handleReload,
        locMap,
        registerModal,
        handleSuccess,
        searchVisible,
        showDrawer,
        register5,
        pickedHouse,
        pickedHouseId,
        houseFirePlaceRef,
        housePolicePlaceRef,
        houseMapRef,
        getTableActs,
        onPopupButtonOkClick,
        fwbhjb1,
        handlePlaceView,
      };
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  #map {
    height: calc(100vh - 140px);
  }

  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }

  .root-house-mng-main {
    margin: 6px;
  }

  .x-village-tabs {
    //z-index: 100;
    //position: absolute;
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    //background-color: rgba(34, 34, 34, 0.6);
    :deep(.ant-form) {
      margin-top: 6px;
    }

    // :deep(.ant-form-item-label) > label {
    //   color: white;
    // }
  }
</style>
